/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.currentsystem.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.view.DownloadView;
import ssn.common.web.CommonController;
import ssn.currentsystem.service.CurrentSystemService;
import ssn.currentsystem.vo.CurrentSystemVO;
import ssn.servicearea.service.ServiceAreaService;
import ssn.servicearea.vo.ServiceAreaVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2013.10.09           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings({"rawtypes","unchecked"})
@Controller
public class CurrentSystemController extends CommonController{
	
    @Resource(name = "currentSystemService")
    private CurrentSystemService currentSystemService;
    
    @Resource(name = "serviceareaService")
    private ServiceAreaService serviceareaService;

    /**
	 * 글 목록을 조회한다(부모 리스트) 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/currentSystem/currentServiceareaList.do")
    public String serviceAreaList(@ModelAttribute("serviceareaVO") ServiceAreaVO serviceareaVO,
    			ModelMap model) throws Exception {
    	if(!loginSessionInfo.get().isAdmin()){
    		return "redirect:/currentSystem/currentSystemList.do";
    	}
    	Map resultMap = serviceareaService.selectServiceAreaList(serviceareaVO);
    	List resultList = (List)resultMap.get("resultList");
    	serviceareaVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("zoneList", resultMap.get("zoneList"));
    	model.addAttribute("serviceareaVO", serviceareaVO);
        
        return "/currentSystem/currentServiceareaList";
    }
    
    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/currentSystem/currentSystemList.do")
    public String currentSystemList(@ModelAttribute("currentSystemVO") CurrentSystemVO currentSystemVO,
    			ModelMap model) throws Exception {
    	
    	/** pageUnit : 페이지 리스트 개수, pageSize : 페이징 개수
    	currentSystemVO.setPageUnit(15);
    	currentSystemVO.setPageSize(15);
    	*/
    	if(!loginSessionInfo.get().isAdmin()){
    		currentSystemVO.setScs_area_key(loginSessionInfo.get().getSsa_area_key());
    	}else{
    		if(EgovStringUtil.isEmpty(currentSystemVO.getScs_area_key())){
    			return "redirect:/currentSystem/currentServiceareaList.do";
    		}
    	}
    	Map resultMap = currentSystemService.selectCurrentSystemList(currentSystemVO);
    	List resultList = (List)resultMap.get("resultList");
    	currentSystemVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("currentSystemVO", currentSystemVO);
        
        return "/currentSystem/currentSystemList";
    }
    
    /**
     * 시설현황 이력 등록 페이지
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemRecordForm.do")
    public String currentSystemRecordForm(@ModelAttribute("currentSystemVO") CurrentSystemVO currentSystemVO,
    			ModelMap model) throws Exception {
    	
    	if(EgovStringUtil.isEmpty(currentSystemVO.getScs_sys_key())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	CurrentSystemVO resultVO = currentSystemService.selectCurrentSystemInfo(currentSystemVO);
    	if(resultVO != null){
    		resultVO.setSearchParam(currentSystemVO);
    	}
    	
    	model.addAttribute("resultVO", resultVO);
        return "/currentSystem/currentSystemRecordForm";
    }
    
    
    /**
     * 시설현황 글쓰기 수정폼
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemWriteForm.do")
    public String currentSystemWriteForm(@ModelAttribute("currentSystemVO") CurrentSystemVO currentSystemVO,
    			ModelMap model) throws Exception {
    	/*if(!loginSessionInfo.get().isAdmin()){
    		throw new EgovBizException(propertiesService.getString("info.grade.msg"));
    	}*/
    	if(EgovStringUtil.isNotEmpty(currentSystemVO.getScs_sys_key())){
    		CurrentSystemVO resultVO = currentSystemService.selectCurrentSystemInfo(currentSystemVO);
    		if(resultVO != null){
        		resultVO.setSearchParam(currentSystemVO);
        	}
    		model.addAttribute("resultVO", resultVO);
    	}else{
    		model.addAttribute("resultVO", currentSystemVO);
    	}
        return "/currentSystem/currentSystemWriteForm";
    }
    
    
    
    @RequestMapping(value="/currentSystem/currentSystemSave.do", method=RequestMethod.GET)
    public String currentSystemWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/currentSystem/currentSystemWriteForm.do";
    }
    
    /**
     * 시설현황 저장/수정
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemSave.do", method=RequestMethod.POST)
    public String currentSystemSave(@ModelAttribute("currentSystemVO") @Valid CurrentSystemVO currentSystemVO, BindingResult bindingResult, RedirectAttributes redirectAttr) throws Exception {
		if(bindingResult.hasErrors()){
			for(FieldError error :  bindingResult.getFieldErrors()){
				redirectAttr.addFlashAttribute("error_"+error.getField(), error.getDefaultMessage());
    		}
			redirectAttr.addFlashAttribute("currentSystemVO", currentSystemVO);
			return "redirect:/currentSystem/currentSystemWriteForm.do";
		}
		if(EgovStringUtil.isNotEmpty(currentSystemVO.getScs_sys_key())){
			currentSystemService.updateCurrentSystemInfo(currentSystemVO);
		}else{
			currentSystemService.insertCurrentSystemInfo(currentSystemVO);
		}
		redirectAttr.addFlashAttribute("msg", "저장 되었습니다.");
		redirectAttr.addAttribute("scs_area_key", currentSystemVO.getScs_area_key());
    	redirectAttr.addAttribute("scs_sys_key", currentSystemVO.getScs_sys_key());
    	redirectAttr.addAttribute("pageIndex", currentSystemVO.getPageIndex());
    	return "redirect:/currentSystem/currentSystemWriteForm.do";
    }
    
    /**
     * 시설현황 저장/수정
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemRecordSave.do", method=RequestMethod.POST)
    public String currentSystemRecordSave(@ModelAttribute("currentSystemVO") @Valid CurrentSystemVO currentSystemVO, BindingResult bindingResult, RedirectAttributes redirectAttr) throws Exception {
    	currentSystemService.updateCurrentSystemOtherInfo(currentSystemVO);
   		redirectAttr.addFlashAttribute("msg", "저장 되었습니다.");
   		redirectAttr.addAttribute("scs_area_key", currentSystemVO.getScs_area_key());
    	redirectAttr.addAttribute("scs_sys_key", currentSystemVO.getScs_sys_key());
    	redirectAttr.addAttribute("pageIndex", currentSystemVO.getPageIndex());
    	return "redirect:/currentSystem/currentSystemRecordForm.do";
    }
    
    /**
     * 삭제
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemDelete.do", method=RequestMethod.POST)
    public ModelAndView currentSystemDelete(@ModelAttribute("currentSystemVO") CurrentSystemVO currentSystemVO) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/currentSystem/currentSystemList.do"));
		if(EgovStringUtil.isNotEmpty(currentSystemVO.getScs_sys_key())){
			currentSystemService.deleteCurrentSystemInfo(currentSystemVO);
		}else{
			throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
		}
    	mav.addObject("scs_area_key", currentSystemVO.getScs_area_key());
    	mav.addObject("pageIndex", currentSystemVO.getPageIndex());
    	return mav;
    }
    
    /**
     * 엑셀 파일 등록폼
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemExcelForm.do")
    public String currentSystemExcelForm(@RequestParam(value="scs_area_key") String scs_area_key,
    			ModelMap model) throws Exception {
    	/*if(!loginSessionInfo.get().isAdmin()){
    		throw new EgovBizException(propertiesService.getString("info.grade.msg"));
    	}*/
    	ServiceAreaVO resultVO = new ServiceAreaVO();
    	resultVO.setSsa_area_key(scs_area_key);
    	resultVO = serviceareaService.selectServiceAreaInfo(resultVO);
    	model.addAttribute("resultVO", resultVO);
        return "/currentSystem/currentSystemExcelForm";
    }
    
    @RequestMapping(value="/currentSystem/currentSystemExcelSave.do", method=RequestMethod.GET)
    public String currentSystemExcelSaveGet(RedirectAttributes redirectAttr) throws Exception {
    	return "redirect:/currentSystem/currentSystemList.do";
    }
    
    /**
     * 설비 관리엑셀 정보 등록
     * @param currentSystemVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/currentSystem/currentSystemExcelSave.do", method=RequestMethod.POST)
    public String currentSystemExcelSave(@RequestParam(value="scs_area_key") String scs_area_key,
    											@RequestParam(value="scs_excel_file") String scs_excel_file,
    											RedirectAttributes redirectAttr ) throws Exception {
    	
    	String[] cellInfo = {"scs_sys_num","scs_sys_name","scs_sys_type","scs_sys_unit","scs_sys_qty","scs_sys_spec","scs_sys_power","scs_sys_note"};
    	String resultMsg = "업로드 실패";
    	
    	Map paramMap = new HashMap();
    	paramMap.put("scs_area_key", scs_area_key);
    	paramMap.put("scs_excel_file", scs_excel_file);
    	paramMap.put("cellInfo", cellInfo);
    	
    	Map resultMap = currentSystemService.insertCurrentSystemInfoExcel(paramMap);
    	if(resultMap != null){
    		int total = (Integer)resultMap.get("totalRow");
    		int icnt = (Integer)resultMap.get("insertRow");
    		resultMsg = "총 "+total+"건 \\n성공 "+icnt+"건\\n살패 "+(total-icnt)+"건";
    	}
    	
    	redirectAttr.addAttribute("scs_area_key",scs_area_key);
    	redirectAttr.addFlashAttribute("msg", resultMsg);
    	return "redirect:/currentSystem/currentSystemExcelForm.do";
    } 
    
    @RequestMapping("/currentSystem/sampleExcelDownload.do")
	public ModelAndView fileDownload() throws IOException{
		
		ModelAndView mav = new ModelAndView(new DownloadView());
		String savePath = propertiesService.getString("file.real.path");
		File file = new File(savePath+"/sample/excel_upload_sample.xls");
		mav.addObject("file", file);
		mav.addObject("fileName", "excel_upload_sample.xls");
		return mav;
	}
}
